package day10.gec.dl死锁2;

class DeadLock implements Runnable {
    int flag;

    // 创建两个对象
    static Object obj = new Object();
    static Object obj2 = new Object();

    @Override
    public void run() {
        if (flag == 1) {
            synchronized (obj) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (obj2) {
                    System.out.println("1");
                }
            }
        }
        if (flag == 0) {
            synchronized (obj2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj) {
                    System.out.println("0");
                }
            }
        }
    }
}

public class DeadLockDemo {
    public static void main(String[] args) {
        DeadLock d1 = new DeadLock();
        d1.flag = 1;
        DeadLock d2 = new DeadLock();
        d2.flag = 0;

        Thread t = new Thread(d1);
        Thread t2 = new Thread(d2);

        t.start();
        t2.start();
    }
}
